package com.shuwang.publicsecurity.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.location.LocationClientOption.LocationMode;
import com.google.gson.Gson;
import com.qzshitong.HttpParameter;
import com.shuwang.publicsecurity.Constants;
import com.shuwang.publicsecurity.R;
import com.shuwang.publicsecurity.entity.PoliceNoBeanJson;
import com.shuwang.publicsecurity.task.AbstractPostAsyncTask1;
import com.shuwang.publicsecurity.task.AsyncCallBack;
import com.shuwang.publicsecurity.ui.AddOrUpdateSupervisionProblemActivity.MyLocationListener;
import com.shuwang.publicsecurity.util.LogUtil;
import com.shuwang.publicsecurity.view.MyTitleBarView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 单位和个人添加页面
 */
public class AddOrUpdateSupervisionProblemAccomplishActivity extends Activity
		implements OnClickListener {
	private static final String TAG = "AddOrUpdateSupervisionProblemAccomplishActivity";
	public BDLocationListener myListener = new MyLocationListener(); // 定位
	public LocationClient mLocationClient = null;

	private Map<String, String> paramPolice;// 负责任警号查询
	private int unitOrPersonal, violateRule;

	private Gson gson;
	private Context mContext;
	private ViewPager viewPager;
	private ArrayList<View> pageview;
	private ImageView im_unit, im_personage;
	// 自定义title
	protected MyTitleBarView mTitleBarView;
	protected ImageView mImageViewLeft;
	private boolean isUpdate;
	private AutoCompleteTextView warning_signal, mAutoBeInspectChargeNo;// 个人
	private AutoCompleteTextView txt_record;// 单位
	private EditText mEditRecorderAddress;
	private Button mButtnLocation;// 定位

	private ArrayAdapter<String> arrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		init();
		mContext = this;
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		viewPager = (ViewPager) findViewById(R.id.viewPager);
		view();
		// 滑动
		showSlide();
		initTitleView();

	}

	void init() {
		paramPolice = new HashMap<String, String>();
	}

	public void view() {
		mTitleBarView = (MyTitleBarView) findViewById(R.id.title_bar);
		mImageViewLeft = (ImageView) mTitleBarView
				.findViewById(R.id.iv_title_left_back);

		// 查找布局文件用LayoutInflater.inflate
		LayoutInflater inflater = getLayoutInflater();
		View view1 = inflater.inflate(R.layout.activity_add_supervision_unit,
				null);// 单位布局
		View view2 = inflater.inflate(
				R.layout.activity_add_supervision_personage, null);// 个人布局
		pageview = new ArrayList<View>();
		pageview.add(view1);
		pageview.add(view2);

		mButtnLocation = (Button) view1.findViewById(R.id.select_address_Btn); // 定位
		mButtnLocation.setOnClickListener(this);
		mEditRecorderAddress = (EditText) view1
				.findViewById(R.id.et_recorder_address); // 单位定位输入框
		txt_record = (AutoCompleteTextView) view1
				.findViewById(R.id.et_inspect_question_name);// 单位记录人输入
		txt_record.setOnClickListener(this);
		mAutoBeInspectChargeNo = (AutoCompleteTextView) view1
				.findViewById(R.id.charge_no_Edit);// 单位负责人

		warning_signal = (AutoCompleteTextView) view2
				.findViewById(R.id.ed_be_inspect_personage_name);// 个人记录人

		im_personage = (ImageView) findViewById(R.id.img_personage);
		im_unit = (ImageView) findViewById(R.id.img_unit);
		im_personage.setOnClickListener(this);
		im_unit.setOnClickListener(this);
		mImageViewLeft.setOnClickListener(this);
		warning_signal.setOnClickListener(this);
		mAutoBeInspectChargeNo.setOnClickListener(this);

	}

	private void initTitleView() {
		mTitleBarView.setCommonTitle(View.VISIBLE, View.VISIBLE);
		if (isUpdate) {
			mTitleBarView.setTitleText("修改督办问题");
			return;
		}
		mTitleBarView.setTitleText(R.string.add_inspector_details);
	}

	// 页面滑动
	public void showSlide() {

		// 数据适配器
		PagerAdapter mPagerAdapter = new PagerAdapter() {

			@Override
			// 获取当前窗体界面数
			public int getCount() {
				// TODO Auto-generated method stub
				return pageview.size();
			}

			@Override
			// 断是否由对象生成界面
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			// 是从ViewGroup中移出当前View
			public void destroyItem(View arg0, int arg1, Object arg2) {
				((ViewPager) arg0).removeView(pageview.get(arg1));
			}

			// 返回一个对象，这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
			public Object instantiateItem(View arg0, int arg1) {
				((ViewPager) arg0).addView(pageview.get(arg1));
				return pageview.get(arg1);
			}

		};
		// 绑定适配器
		viewPager.setAdapter(mPagerAdapter);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_personage:
			viewPager.setCurrentItem(1);
			Toast.makeText(mContext, "个人", Toast.LENGTH_LONG).show();
			break;
		case R.id.img_unit:
			viewPager.setCurrentItem(0);
			Toast.makeText(mContext, "单位", Toast.LENGTH_LONG).show();
			break;
		case R.id.iv_title_left_back:
			finish();
			break;
		case R.id.ed_be_inspect_personage_name:
			// 个人记录姓名
			String[] arr = { "aa", "aab", "aac" };
			arrayAdapter = new ArrayAdapter<String>(mContext,
					android.R.layout.simple_dropdown_item_1line, arr);

			warning_signal.setAdapter(arrayAdapter);
			/*
			 * Toast.makeText(getApplicationContext(), "shurukuang",
			 * Toast.LENGTH_LONG).show();
			 */
			break;

		case R.id.select_address_Btn:
			mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
			mLocationClient.registerLocationListener(myListener); // 注册监听函数
			mLocationClient.start();
			initLocation();

			Toast.makeText(
					AddOrUpdateSupervisionProblemAccomplishActivity.this, "定位",
					Toast.LENGTH_LONG).show();
			break;

		case R.id.et_inspect_question_name:
			Toast.makeText(getApplicationContext(), "单位记录人信息",
					Toast.LENGTH_LONG).show();
			// 单位记录人信息
			String[] arr1 = { "11", "112", "123" };
			arrayAdapter = new ArrayAdapter<String>(
					AddOrUpdateSupervisionProblemAccomplishActivity.this,
					android.R.layout.simple_dropdown_item_1line, arr1);
			txt_record.setAdapter(arrayAdapter);
			break;

		case R.id.charge_no_Edit:
			Toast.makeText(getApplicationContext(), "单位负责人信息",
					Toast.LENGTH_LONG).show();
			// 单位记录人信息
			String[] arr2 = { "11", "112", "123" };
			arrayAdapter = new ArrayAdapter<String>(mContext,
					android.R.layout.simple_dropdown_item_1line, arr2);
			mAutoBeInspectChargeNo.setAdapter(arrayAdapter);
			break;
		default:
			break;
		}

	}

	private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		// int span = 1000; //两小时调用一次接口 120*60*1000
		// option.setScanSpan(span);//
		// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
		option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
	}

	// 把定位的信息放到EditText
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());// 单位：公里每小时
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\nheight : ");
				sb.append(location.getAltitude());// 单位：米
				sb.append("\ndirection : ");
				sb.append(location.getDirection());// 单位度
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				// 运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
				sb.append("\ndescribe : ");
				sb.append("网络定位成功");
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			List<Poi> list = location.getPoiList();// POI数据
			if (list != null) {
				sb.append("\npoilist size = : ");
				sb.append(list.size());
				for (Poi p : list) {
					sb.append("\npoi= : ");
					sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
				}
			}
			Log.i(TAG, sb.toString());
			String address = String.valueOf(location.getAddrStr());
			mEditRecorderAddress.setText(address);
		}
	}

	/**
	 * 查询负责人警号异步类
	 */
	class SearchPolicNoAsyncTask extends
			AbstractPostAsyncTask1<Void, Void, PoliceNoBeanJson> {

		public SearchPolicNoAsyncTask(Class<PoliceNoBeanJson> t,
				AsyncCallBack asyncCallBack, Context context) {
			super(t, asyncCallBack, context);
		}

		@Override
		protected HttpParameter getHttpParameter(Void... params) {

			paramPolice.put("policeName", mAutoBeInspectChargeNo.getText()
					.toString());

			LogUtil.e("unitOrPersonal", String.valueOf(unitOrPersonal));
			LogUtil.e("policeName", paramPolice.get("policeName"));
			paramPolice.put("type", "14");
			String result = gson.toJson(paramPolice);
			// 使用自定义编码，若使用没有参数的构造方法，则默认UTF-8
			HttpParameter httpParameter = new HttpParameter("UTF-8");
			// httpParameter.setPostData 为当 HTTP 请求有POST请求的时候，才需要
			httpParameter.setPostData(result);
			return httpParameter;
		}

		@Override
		protected String getServiceId() {
			return Constants.NOTICE_SERVICEID;
		}

	}

}
